#include "pch.hpp"

#include "ItemSpawn.h"
#include "BallType.h"

const float SPAWN_TIME = 1.0f;

static sf::Sprite stone_spr;
static sf::Image stone_img;
static bool stone_loaded = false;

ItemSpawn::ItemSpawn(): ball_type((BallType::Type)(rand() % BallType::Count)), anim_time(1)
{
}

void ItemSpawn::init(sf::Vector2f pos, int iCount)
{
	position = pos;
	ball_type = (BallType::Type)(rand() % iCount);
	sprite.SetImage(GetBallImage(ball_type));
	sf::Image &img = GetBallImage(ball_type);
	sprite.SetCenter(img.GetWidth()/2.0f, img.GetHeight()/2.0f);
	if(!stone_loaded)
	{
		stone_img.LoadFromFile("data/stone_edge.png");
		stone_spr.SetImage(stone_img);
		stone_spr.SetCenter(stone_img.GetWidth()/2.0f, stone_img.GetHeight()/2.0f);
	}
	stone_loaded = true;
}

void ItemSpawn::step()
{
	anim_time -= 1.0f/60.0f/SPAWN_TIME;
}

void ItemSpawn::draw()
{
	sf::Vector2f add(0,0);
	if(anim_time > 0)
	{
		sprite.SetColor(sf::Color(255,255,255,255*(1-anim_time)));
		add.x = rand() % 3 - 1;
		add.y = rand() % 3 - 1;
	} else
		sprite.SetColor(sf::Color(255,255,255,255));

	stone_spr.SetPosition(position+add);
	directToVector(stone_spr, position-sf::Vector2f(0, 768/2.0f));
	app.Draw(stone_spr);

	sprite.SetPosition(position+add);
	app.Draw(sprite);
}

BallType::Type ItemSpawn::get_type()
{
	return ball_type;
}

void ItemSpawn::clear(int iCount)
{
	ball_type = (BallType::Type)(rand() % iCount);
	if (rand() % 5 == 0)
	{
		ball_type = (BallType::Type)(BallType::Count + 1 + rand() % 2);
	}
	anim_time = 1;

	sprite = sf::Sprite();
	sprite.SetImage(GetBallImage(ball_type));
	sf::Image &img = GetBallImage(ball_type);
	sprite.SetCenter(img.GetWidth()/2.0f, img.GetHeight()/2.0f);
}

sf::Vector2f ItemSpawn::get_position()
{
	return position;
}